<template>
  <div class="roleManagement-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="24">
        <el-button icon="el-icon-plus" type="primary" @click="handleAdd">添加员工</el-button>
        <el-button icon="el-icon-delete" type="danger" @click="handleDelete">批量删除</el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="24">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item label="员工姓名">
            <el-input v-model.trim="queryForm.employeeName" clearable placeholder="请输入员工姓名" />
          </el-form-item>
          <el-form-item label="所在仓库">
            <el-select v-model="queryForm.warehouseId" clearable placeholder="请选择所在仓库">
              <el-option label="全部" value="" />
              <el-option v-for="warehouse in warehouseData" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="工作状态">
            <el-select v-model="queryForm.workStatus" clearable placeholder="请选择工作状态">
              <el-option label="全部" value="" />
              <el-option v-for="(label, value) in workStatusMap" :key="value" :label="label" :value="value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
            <el-button @click="resetQueryForm">重置</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      :element-loading-text="elementLoadingText"
      style="width: 100%;"
      @selection-change="setSelectRows"
    >
      <el-table-column show-overflow-tooltip type="selection" />
      <el-table-column label="员工ID" prop="id" show-overflow-tooltip/>
      <el-table-column label="员工姓名" prop="name" show-overflow-tooltip />
      <el-table-column label="所在仓库" prop="warehouseName" show-overflow-tooltip/>
      <el-table-column label="职位" prop="position" show-overflow-tooltip/>
      <el-table-column label="工作状态" prop="workStatus" show-overflow-tooltip>
        <template #default="{ row }">
          <el-tag :type="workStatusTagType[row.workStatus]">{{ workStatusMap[row.workStatus] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="部门" prop="department" show-overflow-tooltip width="120" />
      <el-table-column align="center" label="操作" show-overflow-tooltip width="200">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <!-- 员工编辑弹窗 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '新增员工' : '编辑员工'"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="employeeForm"
        label-position="right"
        label-width="100px"
        :model="employeeForm"
        :rules="rules"
      >
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="employeeForm.name" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="所在仓库" prop="warehouseId">
          <el-select v-model="employeeForm.warehouseId" placeholder="请选择所在仓库">
            <el-option label="未分配" :value="null" />
            <el-option
              v-for="warehouse in availableWarehouses"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作状态" prop="workStatus">
          <el-select v-model="employeeForm.workStatus" placeholder="请选择工作状态">
            <el-option v-for="(label, value) in workStatusMap" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="employeeForm.department" placeholder="请选择部门">
            <el-option v-for="dept in departments" :key="dept" :label="dept" :value="dept" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-select v-model="employeeForm.position" placeholder="请选择职位">
            <el-option v-for="pos in positions" :key="pos" :label="pos" :value="pos" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'EmployeeManagement',
    data() {
      return {
        list: [],
        allEmployeesData: [], // 存储所有员工数据
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: [],
        elementLoadingText: '正在加载...',
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          employeeName: '',
          warehouseId: '',
          workStatus: '',
        },
        timeOutID: null,
        warehouseData: [], // 存储仓库信息
        workStatusMap: { // 工作状态映射
          on_duty: '在岗',
          on_leave: '请假',
          business_trip: '出差',
        },
        workStatusTagType: { // 工作状态标签类型
          on_duty: 'success',
          on_leave: 'warning',
          business_trip: 'info',
        },
        departments: ['技术部', '销售部', '人事部', '市场部', '行政部'],
        positions: ['经理', '主管', '专员', '助理', '总监'],
        // 弹窗相关数据
        dialogVisible: false,
        dialogStatus: 'create', // 'create' 或 'update'
        employeeForm: {
          id: '',
          name: '',
          warehouseId: null,
          workStatus: 'on_duty',
          department: '',
          position: '',
        },
        rules: {
          name: [
            { required: true, message: '请输入员工姓名', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          workStatus: [
            { required: true, message: '请选择工作状态', trigger: 'change' }
          ],
          department: [
            { required: true, message: '请选择部门', trigger: 'change' }
          ],
          position: [
            { required: true, message: '请选择职位', trigger: 'change' }
          ]
        }
      }
    },
    computed: {
      // 获取可用于分配的仓库
      availableWarehouses() {
        // 员工可以被分配到任何一个仓库
        // “一个员工只能在一个仓库”的约束是通过 employeeForm.warehouseId 的单一值来保证的
        return this.warehouseData;
      }
    },
    created() {
      this.loadWarehouseData() // 首先加载仓库数据
      this.loadEmployeeData() // 加载员工数据
    },
    beforeDestroy() {
      clearTimeout(this.timeOutID)
    },
    methods: {
      // 加载仓库数据
      loadWarehouseData() {
        const storedData = localStorage.getItem('warehouseTableData')
        if (storedData) {
          this.warehouseData = JSON.parse(storedData)
        } else {
          // 如果localStorage没有数据，设置默认值
          this.warehouseData = [
            { id: 1, name: '北京中心仓', address: '北京市朝阳区xxx路xxx号', manager: '张三', phone: '13800138000', status: 1 },
            { id: 2, name: '上海配送中心', address: '上海市浦东新区xxx路xxx号', manager: '李四', phone: '13900139000', status: 1 },
            { id: 3, name: '广州仓储中心', address: '广州市天河区xxx路xxx号', manager: '王五', phone: '13700137000', status: 2 },
            { id: 4, name: '深圳物流仓', address: '深圳市南山区xxx路xxx号', manager: '赵六', phone: '13600136000', status: 3 }
          ];
          localStorage.setItem('warehouseTableData', JSON.stringify(this.warehouseData))
        }
      },

      // 加载员工数据
      loadEmployeeData() {
        const storedData = localStorage.getItem('employeeTableData')
        if (storedData) {
          this.allEmployeesData = JSON.parse(storedData)
        } else {
          // 如果localStorage没有数据，设置默认值
          this.allEmployeesData = [
            { id: 'emp001', name: '张三', warehouseId: 1, workStatus: 'on_duty', department: '技术部', position: '经理' },
            { id: 'emp002', name: '李四', warehouseId: 2, workStatus: 'on_duty', department: '销售部', position: '主管' },
            { id: 'emp003', name: '王五', warehouseId: 3, workStatus: 'business_trip', department: '市场部', position: '专员' },
            { id: 'emp004', name: '赵六', warehouseId: 4, workStatus: 'on_leave', department: '人事部', position: '总监' },
            { id: 'emp005', name: '孙七', warehouseId: null, workStatus: 'on_duty', department: '行政部', position: '助理' },
          ];
          this.saveEmployeeData()
        }
        this.fetchData()
      },

      // 保存员工数据到localStorage
      saveEmployeeData() {
        localStorage.setItem('employeeTableData', JSON.stringify(this.allEmployeesData))
      },

      // 设置选中行
      setSelectRows(val) {
        this.selectRows = val
      },

      // 添加员工
      handleAdd() {
        this.dialogStatus = 'create'
        this.resetForm()
        this.dialogVisible = true
      },

      // 编辑员工
      handleEdit(row) {
        this.dialogStatus = 'update'
        this.dialogVisible = true
        this.employeeForm = JSON.parse(JSON.stringify(row))
      },

      // 重置表单
      resetForm() {
        this.employeeForm = {
          id: '',
          name: '',
          warehouseId: null,
          workStatus: 'on_duty',
          department: this.departments[0],
          position: this.positions[0]
        }
        if (this.$refs.employeeForm) {
          this.$refs.employeeForm.resetFields()
        }
      },

      // 提交表单
      submitForm() {
        this.$refs.employeeForm.validate(valid => {
          if (valid) {
            if (this.dialogStatus === 'create') {
              // 创建新员工
              const newEmployee = {
                ...this.employeeForm,
                id: `user${Date.now().toString().slice(-6)}`
              }

              // 更新本地数据
              this.allEmployeesData.push(newEmployee)
              this.$message.success('新增员工成功')
            } else {
              // 更新现有员工
              const index = this.allEmployeesData.findIndex(item => item.id === this.employeeForm.id)
              if (index !== -1) {
                this.allEmployeesData.splice(index, 1, this.employeeForm)
                this.$message.success('更新员工成功')
              }
            }

            // 保存数据并刷新
            this.saveEmployeeData()
            this.dialogVisible = false
            this.fetchData()
          }
        })
      },

      // 删除员工
      handleDelete(row) {
        if (row && row.id) {
          // 删除单个员工
          this.$baseConfirm('你确定要删除该员工吗？', null, () => {
            const index = this.allEmployeesData.findIndex(item => item.id === row.id)
            if (index !== -1) {
              this.allEmployeesData.splice(index, 1)
              this.saveEmployeeData()
              this.$message.success('删除成功')
              this.fetchData()
            }
          })
        } else {
          // 批量删除
          if (this.selectRows.length > 0) {
            this.$baseConfirm('你确定要删除选中的员工吗？', null, () => {
              const ids = this.selectRows.map(item => item.id)
              this.allEmployeesData = this.allEmployeesData.filter(item => !ids.includes(item.id))
              this.saveEmployeeData()
              this.$message.success('批量删除成功')
              this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
          }
        }
      },

      // 处理分页大小变化
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },

      // 处理页码变化
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },

      // 查询数据
      queryData() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },

      // 重置查询表单
      resetQueryForm() {
        this.queryForm = {
          pageNo: 1,
          pageSize: this.queryForm.pageSize,
          employeeName: '',
          warehouseId: '',
          workStatus: '',
        }
        this.fetchData()
      },

      // 获取数据并应用筛选、分页
      fetchData() {
        this.listLoading = true

        // 应用筛选条件
        let filteredData = [...this.allEmployeesData]

        if (this.queryForm.employeeName) {
          filteredData = filteredData.filter(item =>
            item.name && item.name.includes(this.queryForm.employeeName)
          )
        }

        if (this.queryForm.warehouseId) {
          filteredData = filteredData.filter(item =>
            item.warehouseId === Number(this.queryForm.warehouseId)
          )
        }

        if (this.queryForm.workStatus) {
          filteredData = filteredData.filter(item =>
            item.workStatus === this.queryForm.workStatus
          )
        }

        // 添加仓库名称信息
        const dataWithWarehouseName = filteredData.map(emp => {
          const warehouse = this.warehouseData.find(w => w.id === emp.warehouseId)
          return {
            ...emp,
            warehouseName: warehouse ? warehouse.name : '未分配'
          }
        })

        this.total = dataWithWarehouseName.length

        // 分页
        const start = (this.queryForm.pageNo - 1) * this.queryForm.pageSize
        const end = start + this.queryForm.pageSize
        this.list = dataWithWarehouseName.slice(start, end)

        this.timeOutID = setTimeout(() => {
          this.listLoading = false
        }, 300)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .roleManagement-container {
    padding: 20px;

    .filter-container {
      margin-bottom: 20px;
    }

    .table-container {
      margin-top: 20px;
    }
  }
  /* 建议移除或注释掉以下样式，因为 el-table 自身的 width: 100% 通常能更好地处理布局
  ::v-deep .el-table__header-wrapper .el-table__header {
    width: 100%;
  }
  */
</style>
